package com.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pojo.DictionaryItem;
import com.service.DictionaryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/dictionary")
public class DictionaryItemController {

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "10") int pageSize,
                       Model model) {
        PageHelper.startPage(pageNum, pageSize);
        List<DictionaryItem> items = dictionaryItemService.findAll();
        PageInfo<DictionaryItem> pageInfo = new PageInfo<>(items);
        model.addAttribute("pageInfo", pageInfo);
        return "dictionary/dictionaryList";
    }

    @GetMapping("/add")
    public String addPage() {
        return "dictionary/dictionaryAdd";
    }

    @PostMapping("/insert")
    public String insert(DictionaryItem dictionaryItem) {
        dictionaryItemService.insert(dictionaryItem);
        return "redirect:/dictionary/list";
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        DictionaryItem dictionaryItem = dictionaryItemService.findById(id);
        model.addAttribute("dictionaryItem", dictionaryItem);
        return "dictionary/dictionaryEdit";
    }

    @PostMapping("/update")
    public String update(DictionaryItem dictionaryItem) {
        dictionaryItemService.update(dictionaryItem);
        return "redirect:/dictionary/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        dictionaryItemService.deleteById(id);
        return "redirect:/dictionary/list";
    }
}
